package com.xiaomi.service.impl;

import com.xiaomi.dao.ProductDao;
import com.xiaomi.dao.impl.ProductDaoImpl;
import com.xiaomi.entity.Page;
import com.xiaomi.entity.Product;
import com.xiaomi.service.ProductService;

import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/24
 */
public class ProductServiceImpl implements ProductService {

    private final ProductDao productDao = new ProductDaoImpl();

    @Override
    public Page<Product> list(String tid, String curPage) {
        int currentPage = 1;//初始页
        int pageNum = 4;//每页数据量
        int id = 1;//类型id
        Page<Product> page = new Page<>();
        try {
            if (curPage != null && !"".equals(curPage)) {
                currentPage = Integer.parseInt(curPage);
                //分页合理化参数1,传入的currentPage不能为负数
                if (currentPage < 1)
                    currentPage = 1;
            }
            if (tid != null && !"".equals(tid)) {
                id = Integer.parseInt(tid);
            }
            //设置当前页
            page.setCurPage(currentPage);
            //设置每页数据量
            page.setPageNum(pageNum);
            //获取并设置总数据量
            int count = productDao.count(id);
            page.setTotalCount(count);
            //设置总页数
            int totalPage = count % pageNum == 0 ? count / pageNum : count / pageNum + 1;
            page.setTotalPage(totalPage);
            //分页合理化参数1,当前页不能超过最大页数
            if (currentPage > totalPage) {
                currentPage = totalPage;
            }
            //设置当前页产品数据
            int begin = (currentPage - 1) * pageNum;
            List<Product> list = productDao.list(id, begin, pageNum);
            page.setList(list);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Product getProductByPid(String pid) {
        try {
            int id = 1;
            if (pid != null && !"".equals(pid)) {
                id = Integer.parseInt(pid);
            }
            return productDao.getProductByPid(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
